package com.pswv2.backstage.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.pswv2.backstage.user.service.UserService;
import com.pswv2.bub.bsc.dao.po.AdminUser;
import com.pswv2.bub.bsc.dao.po.Authentication;
import com.pswv2.bub.bsc.dao.po.MyWallet;
import com.pswv2.bub.bsc.dao.po.User;
import com.pswv2.bub.bsc.dao.po.UserTerritory;
import com.pswv2.util.BackendErrorCode;
import com.pswv2.util.CommonResp;
import com.pswv2.util.ExtraSpringHibernateTemplate;
import com.pswv2.util.Paging;
import com.pswv2.util.Sessions;

@Controller
@RequestMapping(value = "userAction", produces = { "text/json;charset=UTF-8" })
public class UserAction {
	private static Class<?> poc = User.class;
	private static Class<?> pocUT = UserTerritory.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private UserService userService;
	/**
	 * 通过Id查看详情
	 */
	@ResponseBody
	@RequestMapping(value = { "queryAll" })
	public String queryAll() {
		List<User> ls = userService.queryAll();
		return CommonResp.buildSuccessResp(ls).toJsonString();
	}
	/**
	 * 通过Id查看详情
	 */
	@ResponseBody
	@RequestMapping(value = { "editPassword" })
	public String editPassword(Integer uesrId,String oldPassword,String newPassword,String confirmPassword) {
		User uesr = userService.queryById(uesrId);
		if(uesr.getPassword().equals(oldPassword)){
			if(newPassword.equals(confirmPassword)){
				uesr.setPassword(newPassword);
				extraSpringHibernateTemplate.getHibernateTemplate().update(uesr);
				return CommonResp.buildSuccessResp().toJsonString();
			}else{
				return CommonResp.buildErrorResp(BackendErrorCode.confirm_password_error).toJsonString();
			}
		}else{
			return CommonResp.buildErrorResp(BackendErrorCode.old_password_error).toJsonString();
		}
	}
	/**
	 * 通过Id查看详情
	 */
	@ResponseBody
	@RequestMapping(value = { "setVoice" })
	public String setVoice(Integer uesrId,Integer voice) {
		User uesr = userService.queryById(uesrId);
		uesr.setVoice(voice);
		extraSpringHibernateTemplate.getHibernateTemplate().update(uesr);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 通过Id查看详情
	 */
	@ResponseBody
	@RequestMapping(value = { "queryId" })
	public String queryId(Integer uesrId) {
		User uesr = userService.queryById(uesrId);
		return CommonResp.buildSuccessResp(uesr).toJsonString();
	}
	/**
	 * 后台审核通过
	 */
	@ResponseBody
	@RequestMapping(value = { "platformAdopt" })
	public String platformAdopt(Integer uesrId) {
		User uesr = userService.queryById(uesrId);
		uesr.setStatue(1);
		extraSpringHibernateTemplate.getHibernateTemplate().update(uesr);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 后台审核未通过
	 */
	@ResponseBody
	@RequestMapping(value = { "platformNotAdopt" })
	public String platformNotAdopt(Integer uesrId) {
		User uesr = userService.queryById(uesrId);
		uesr.setStatue(2);
		extraSpringHibernateTemplate.getHibernateTemplate().update(uesr);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 	pc后台选中通过
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnPass"})
	public String pitchOnPass(@RequestParam(value = "items[]") int[] items){
		/*for(int a:items){
			User entity = userService.queryById(a);
			if(entity.getStatue()==User.user_pass||entity.getStatue()==User.user_reject){
				return CommonResp.buildErrorResp(BackendErrorCode.already_auditing).toJsonString();
			}
		}*/
		for(int a:items){
			User entity = userService.queryById(a);
			entity.setStatue(User.user_pass);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 	pc后台选中驳回
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnReject"})
	public String pitchOnReject(@RequestParam(value = "items[]") int[] items){
		/*for(int a:items){
			User entity = userService.queryById(a);
			if(entity.getStatus()==entity.status_pass||entity.getStatus()==entity.status_reject){
				return CommonResp.buildErrorResp(BackendErrorCode.already_auditing).toJsonString();
			}
		}*/
		for(int a:items){
			User entity = userService.queryById(a);
			entity.setStatue(User.user_reject);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 名字条件查询
	 */
	/*@ResponseBody
	@RequestMapping(value = "search")
	public String search(String name) throws ParseException {
		List<Criterion> criterions = new ArrayList<>();
		if (StringUtils.isNoneBlank(name)) {
			criterions.add(Restrictions.ilike("name", "%" + name + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}*/
	/**
	 * 查询待审核的资料编辑
	 * @param pageIndex
	 * @param pageSize
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryList")
	public String queryList(int pageIndex, int pageSize, HttpSession session) {
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.isNotNull("statue"));
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		pageIndex=pageIndex*pageSize;
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, pageIndex, pageIndex);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	/**
	 * appmore详细资料修改
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("editUserDatum")
	public String editUserDatum(@RequestParam(value = "territorys[]")String[] territorys,int userId,
			String name,String workAddress,String workOccupation,String sex,
			String degree,String interest,String strongpoint,String other) {
		User user=userService.queryById(userId);
		user.setName(name);
		user.setSex(sex);
		user.setDegree(degree);
		user.setInterest(interest);
		user.setStrongPoint(strongpoint);
		user.setWorkOccupation(workOccupation);
		user.setWorkAddress(workAddress);
		user.setOther(other);
		user.setStatue(1);
		extraSpringHibernateTemplate.getHibernateTemplate().update(user);
		extraSpringHibernateTemplate.deleteAllByPropEq(pocUT, "userId", userId);
		for(String territoryId : territorys){
			UserTerritory ut=new UserTerritory();
			ut.setTerritoryId(Integer.parseInt(territoryId));
			ut.setUserId(userId);
			extraSpringHibernateTemplate.getHibernateTemplate().save(ut);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * app通过id查询用户资料
	 * @param pageIndex
	 * @param pageSize
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryUserById")
	public String queryUserById(int userId) {
		User user=userService.queryById(userId);
		return CommonResp.buildSuccessResp(user).toJsonString();
	}
	
	@ResponseBody
	@RequestMapping("list")
	public String list(int pageIndex, int pageSize, HttpSession session) {
		pageIndex=pageIndex*pageSize;
		Paging<?> paging = extraSpringHibernateTemplate.findPage(poc, Order.desc("userId"),pageIndex, pageSize);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	@ResponseBody
	@RequestMapping("all")
	public String all(HttpSession session) {
		User loginedUser = (User) Sessions.getLoginedUser(session);
		DetachedCriteria detached = DetachedCriteria.forClass(poc);
		detached.add(Restrictions.eq("memberId", loginedUser.getUserId()));
		return CommonResp.buildSuccessResp(extraSpringHibernateTemplate.findAllByCriteria(detached)).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "updateMyPwd")
	public String updateMyPwd(String newPassword, String password, HttpSession session) {
		User loginedUser = (User) Sessions.getLoginedUser(session);
		User toUpdate = userService.queryByAccount(loginedUser.getAccount());
		if (!toUpdate.getPassword().equals(password)) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_password_not_match).toJsonString();
			
		}
		toUpdate.setPassword(newPassword);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "perfect")
	public String prefect(String name,String age, String carded,String height,String weight,String sex,String interest,Integer id) {
		User toUpdate = userService.queryById(id);
		toUpdate.setAge(age);
		toUpdate.setName(name);
		toUpdate.setCarded(carded);
		toUpdate.setHeight(height);
		toUpdate.setWeight(weight);
		toUpdate.setSex(sex);
		toUpdate.setInterest(interest);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	@ResponseBody
	@RequestMapping(value = "updatePwd")
	public String updatePwd(String newPassword, Integer id) {
		User toUpdate = userService.queryById(id);
		toUpdate.setPassword(newPassword);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "queryDetail")
	public String queryDetail(Integer id) {
		JSONObject resp = new JSONObject();
		resp.put("User", userService.queryById(id));
		resp.put("UserPermission", null);
		return CommonResp.buildSuccessResp(resp).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		User toDelete = userService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String realname, String phone, HttpSession session) {
		User loginedUser = (User) Sessions.getLoginedUser(session);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", loginedUser.getUserId()));
		if (StringUtils.isNoneBlank(realname)) {
			criterions.add(Restrictions.like("realname", "%" + realname + "%"));
		}
		if (StringUtils.isNoneBlank(phone)) {
			criterions.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}
	@ResponseBody
	@RequestMapping(value = "searchs")
	public String searchs(String realname, String phone, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", loginedUser.getAdminUserId()));
		if (StringUtils.isNoneBlank(realname)) {
			criterions.add(Restrictions.like("realname", "%" + realname + "%"));
		}
		if (StringUtils.isNoneBlank(phone)) {
			criterions.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}
	
	/**
	 * 注册账号
	 * @param account
	 * @param password
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "add")
	public String add( String password, String account,HttpSession session) {
		List<User> ls=extraSpringHibernateTemplate.findAllByPropEq(poc, "account", account);
		if(ls.size()==0){
			User toSave = new User();
			toSave.setPassword(password);
			toSave.setAccount(account);
			toSave.setPoints(1000);
			toSave.setCreditValue(100);
			toSave.setVoice(-1);
			extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
			Integer userId=toSave.getUserId();
			MyWallet mw=new MyWallet();
			mw.setUserId(userId);
			mw.setMoney(0);
			extraSpringHibernateTemplate.getHibernateTemplate().save(mw);
			Sessions.setLoginedUser(toSave,session);
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
			return CommonResp.buildErrorResp(BackendErrorCode.account_exist).toJsonString();
		}
	}
	/**
	 * 注册账号
	 * @param account
	 * @param password
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "add1")
	public String add1( String password, String account,HttpSession session) {
		List<User> ls=extraSpringHibernateTemplate.findAllByPropEq(poc, "account", account);
		if(ls.size()==0){
			User toSave = new User();
			toSave.setPassword(password);
			toSave.setAccount(account);
			toSave.setName(account);
			toSave.setPoints(1000);
			toSave.setCreditValue(100);
			toSave.setVoice(-1);
			toSave.setStatue(1);
			extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
			Authentication entity =new Authentication();
			entity.setUserId(toSave.getUserId());
			entity.setStatus(1);
			extraSpringHibernateTemplate.getHibernateTemplate().save(entity);
			Integer userId=toSave.getUserId();
			MyWallet mw=new MyWallet();
			mw.setUserId(userId);
			mw.setMoney(0);
			extraSpringHibernateTemplate.getHibernateTemplate().save(mw);
			Sessions.setLoginedUser(toSave,session);
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
			return CommonResp.buildErrorResp(BackendErrorCode.account_exist).toJsonString();
		}
	}
	
	/**
	 * 添加安全提问便于找回密码
	 * @param passwordQuestion
	 * @param passwordKey
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "safeSet")
	public String safeSet(String passwordQuestion, String passwordKey,Integer id) {
		User toUpdate = userService.queryById(id);
		toUpdate.setPasswordQuestion(passwordQuestion);
		toUpdate.setPasswordKey(passwordKey);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * app添加安全提问便于找回密码
	 * @param passwordQuestion
	 * @param passwordKey
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "safeSetInner")
	public String safeSetInner(Integer id) {
		User user = userService.queryById(id);
		String passwordQuestion = user.getPasswordQuestion();
		String passwordKey =user.getPasswordKey();
		if(passwordQuestion!=null&&passwordKey!=null){
			return CommonResp.buildSuccessResp(user).toJsonString();
		}
		return CommonResp.buildErrorResp(BackendErrorCode.not_password_question_key).toJsonString();
		
	}
	/**
	 * app通过用户名查找用户类
	 * @param account
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "findAccount")
	public String findAccount(String account) {
		List<User> listUser = (List<User>) extraSpringHibernateTemplate.getHibernateTemplate().find("From User where account=?", account);
		if(listUser.size()==0){
			return CommonResp.buildErrorResp(BackendErrorCode.account_exist).toJsonString();
		}else{
			return CommonResp.buildSuccessResp(listUser.get(0)).toJsonString();
		}
		
	}
	/**
	 * app答案是否正确
	 * @param passwordQuestion
	 * @param passwordKey
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "safeRetrieve")
	public String safeRetrieve(String passwordQuestion, String passwordKey,Integer id) {
		User user = userService.queryById(id);
		String passwordKey1=user.getPasswordKey();
		if(passwordKey1.equals(passwordKey)){
			return CommonResp.buildSuccessResp().toJsonString();
		}else {
			return CommonResp.buildErrorResp(BackendErrorCode.password_key_error).toJsonString();
		}
	}
	/**
	 * app获取问题
	 * @param passwordQuestion
	 * @param passwordKey
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "safeGetQuestion")
	public String safeGetQuestion(Integer id) {
		User user = userService.queryById(id);
		return CommonResp.buildSuccessResp(user).toJsonString();
		          
	}
	/**
	 * app修改密码
	 * @param newPassword
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "editPwd")
	public String editPwd(String newPassword, Integer id) {
		User toUpdate = userService.queryById(id);
		toUpdate.setPassword(newPassword);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp(toUpdate).toJsonString();
	}
	/**
	 * app检测用户是否完善资料
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkUserWhetherPerfect")
	public String checkUserWhetherPerfect(Integer id) {
		User user = userService.queryById(id);
		String degree=user.getDegree();
		String interest=user.getInterest();
		String strongPoint=user.getStrongPoint();
		String sex=user.getSex();
		if(degree==null&&interest==null&&strongPoint==null&&sex==null){
			return CommonResp.buildErrorResp(BackendErrorCode.Incomplete_data).toJsonString();
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * app用户完善资料
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "userPerfect")
	public String userPerfect(Integer id,String degree,String interest,String strongPoint,String sex) {
		User user = userService.queryById(id);
		user.setDegree(degree);
		user.setInterest(interest);
		user.setStrongPoint(strongPoint);
		user.setSex(sex);
		extraSpringHibernateTemplate.getHibernateTemplate().update(user);
		return CommonResp.buildSuccessResp().toJsonString();
	}

}
